layui.define(['element', 'api', 'fast_config', 'utils', 'form'], function (exports) {
    "use strict";

    /**
     * Button component
     * */
    var MOD_NAME = 'domain_design_business',
        $ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config,
        form = layui.form,
        utils = layui.utils,
        rowIndex;

    var domain_design_business = function (opt) {
        this.option = opt;
    };

    var initFieldDate = function (option) {
        option.fields = {};
    }

    function openModel(rowIndx, rowdata, grid) {
        let contenthtml=``;
        if(rowdata.defaultValueType ==='Sequence'){
            let op = '';
            api.exec({
                enableRootPath: true,
                type: "GET",
                url: utils.stringformat(fast_config.app.seqApi),
                success: function (data) {
                    for (let i = 0; i < data.length; i++) {
                        op = op + `<option value="${data[i].id}">${data[i].seq}</option>`;
                    }
                }
            });
            contenthtml = `
                    <form name="myForm" class="layui-form" lay-filter='myForm' style="width: 500px; height: 200px" action="">
                    <div class="layui-form-item">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-block"> 
                      <select name="defaultValueType" lay-verify="required" lay-filter="type"> 
                        <option value="">-请选择-</option>
                        <option value="Constant">常量</option>
                        <option value="EL">EL表达式</option>
                        <option value="Sequence">值选择器</option>
                      </select>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">默认值</label>
                    <div class="layui-input-block" id="dval">
                        <select id="seqval" name="defaultValue" lay-verify="required" lay-filter="seqval">
                        ${op}
                        </select>
                        
                    </div>
                  </div>
                </form>
                    `
        }else{
            contenthtml = `
                    <form name="myForm" class="layui-form" lay-filter='myForm' style="width: 500px; height: 200px" action="">
                    <div class="layui-form-item">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-block"> 
                      <select name="defaultValueType" lay-verify="required" lay-filter="type"> 
                        <option value="">-请选择-</option>
                        <option value="Constant">常量</option>
                        <option value="EL">EL表达式</option>
                        <option value="Sequence">值选择器</option>
                      </select>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">默认值</label>
                    <div class="layui-input-block" id="dval">
                        <input type="text" name="defaultValue" autocomplete="off" class="layui-input">
                    </div>
                  </div>
                </form>
                    `
        }
        layer.open({
            type: 1,
            title: "设置",
            offset: '30%',
            zIndex: 100,
            success: function () {
                form.render(null, 'myForm');
            },
            content: contenthtml,
            shade: 0.3,
            btn: ['提交', '取消'],
            btn1: function (index, layero) {
                let formData = form.val('myForm');
                rowdata = {
                    ...rowdata,
                    ...formData
                }
                // let upIndx = rowIndx-1;
                grid.deleteRow({
                    rowIndx: rowIndx
                });
                grid.addRow({
                    newRow: rowdata,
                    rowIndx: rowIndx
                })
                grid.getData();
                layer.closeAll();
            },
            btn2: function () {
                layer.closeAll();
            },
            cancel: function (layero, index) {
                layer.closeAll();
            }
        });
    }

    layui.use(['form'], function () {
        form = layui.form;
        form.on('select(type)', function (data) {
            var val = data.value;
            // console.info(val);

            $("#dval").html("");

            if (val == "Constant" || val == "EL") {
                $("#dval").append(`<input type="text" name="defaultValue" autocomplete="off" class="layui-input">`);
            }
            if (val == "Sequence") {

                let seqhtml = `<select id="seqval" name="defaultValue" lay-verify="required" lay-filter="seqval"></select>`;
                let op = '<option value="">-请选择-</option>';
                api.exec({
                    enableRootPath: true,
                    type: "GET",
                    url: utils.stringformat(fast_config.app.seqApi),
                    success: function (data) {
                        for (let i = 0; i < data.length; i++) {
                            op = op + `<option value="${data[i].id}">${data[i].seq}</option>`;
                        }
                    }
                });

                $("#dval").append(seqhtml);

                $("#seqval").append(op);
            }

            form.render('select');
        });
    });

    /**
     * Button start loading
     * */
    domain_design_business.prototype.render = function (opt) {

        var option = {
            elem: opt.elem,
            initData: opt.initData,
            grid: null
        }

        initFieldDate(option);

        var grid;
        var parentContextData = window.parent.window.contextData;
        // var path = parentContextData.contextmenuData.data.path;
        var metaName;


        var dateEditor = function (ui) {
            var $inp = ui.$cell.find("input"),
                grid = this,
                validate = function (that) {
                    var valid = grid.isValid({
                        dataIndx: ui.dataIndx,
                        value: $inp.val(),
                        rowIndx: ui.rowIndx
                    }).valid;
                    if (!valid) {
                        that.firstOpen = false;
                    }
                };

            //initialize the editor
            $inp
                .on("input", function (evt) {
                    validate(this);
                })
                .datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showAnim: '',
                    dateFormat: 'yy-mm-dd',
                    onSelect: function () {
                        this.firstOpen = true;
                        validate(this);
                    },
                    beforeShow: function (input, inst) {
                        return !this.firstOpen;
                    },
                    onClose: function () {
                        this.focus();
                    }
                });
        }


        //called when save changes button is clicked.
        function saveChanges() {

            //attempt to save editing cell.
            if (grid.saveEditCell() === false) {
                return false;
            }

            if (grid.isDirty() && grid.isValidChange({
                    focusInvalid: true
                }).valid) {

                var changes = grid.getChanges({
                    format: "byVal"
                });

                //post changes to server
                api.post({
                    enableRootPath: true,
                    dataType: "json",
                    type: "POST",
                    async: true,
                    beforeSend: function (jqXHR, settings) {
                        grid.showLoading();
                    },
                    url: "/meta/" + metaName + "/batch",
                    // contextT
                    data: JSON.stringify(changes),
                    headers: {
                        'Content-Type': 'application/json;charset=utf8'
                    },
                    success: function (changes) {
                        grid.commit({
                            type: 'add',
                            rows: changes.addList
                        });
                        grid.commit({
                            type: 'update',
                            rows: changes.updateList
                        });
                        grid.commit({
                            type: 'delete',
                            rows: changes.deleteList
                        });

                        grid.history({
                            method: 'reset'
                        });
                    },
                    complete: function () {
                        grid.hideLoading();
                    }
                });
            }
        }

        //获取url中的参数
        function getUrlParam(url, name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = url.substr(1).match(reg); //匹配目标参数
            if (r != null) return unescape(r[2]);
            return null; //返回参数值
        }

        var types = [{
                "id": "basic",
                "value": "basic",
                "name": "基础类型"
            },
            {
                "id": "dd",
                "value": "dd",
                "name": "数据字典"
            },
            {
                "id": "mdm",
                "value": "mdm",
                "name": "基础数据"
            }
        ];

        var data = [];
        if (option.initData) {
            data = option.initData;
            for (var field of data) {
                if (field["validationTypeList"] != undefined && field["validationTypeList"].length > 0) {
                    for (var vali of field["validationTypeList"]) {
                        field[vali] = true;
                    }
                }
                field.pq_rowselect = undefined;
                field.state = false;
                field["validationTypeList"] = null;
            }
        }


        function getFieldClass(type) {
            if (!option.fields[type]) {
                api.exec({
                    enableRootPath: true,
                    type: "GET",
                    // url: fast_config.domain.fieldClassApi+type,
                    url: fast_config.moudle.domain.fieldClassApi.format({
                        type: type
                    }),
                    success: function (data) {
                        // console.log("data",JSON.parse(data));
                        option.fields[type] = data;
                    }
                });
            }

            return option.fields[type];
        }

        var fieldClass = function (ui) {
            let type = ui.rowData.fieldType;
            if (type == '') {
                type = "basic";
            }
            return getFieldClass(type);
        }

        var obj = {
            hwrap: false,
            virtualX: true,
            rowBorders: false,
            trackModel: {
                on: true
            }, //to turn on the track changes.
            // selectionModel: { type: 'row' },
            selectionModel: {
                type: null
            },
            toolbar: {
                items: [{
                        type: 'button',
                        icon: 'ui-icon-plus',
                        label: '',
                        listener: function () {
                            //append empty row at the end.

                            let i = grid.getData().length + 1;
                            let rowData = {
                                fieldComment: "字段" + i,
                                fieldName: "field" + i,
                                columnName: "",
                                fieldType: "basic",
                                fieldClass: "String",
                                canExcel: false,
                                apiHide: false
                            }; //default row
                            let rowIndx = grid.addRow({
                                rowData: rowData,
                                checkEditable: true
                            });
                            grid.goToPage({
                                rowIndx: rowIndx
                            });
                            grid.editFirstCellInRow({
                                rowIndx: rowIndx
                            });
                        }
                    },
                    {
                        type: 'button',
                        icon: 'ui-icon-close',
                        label: '',
                        listener: function () {
                            //debugger
                            if (rowIndex != null) {
                                layer.confirm('确认删除选中数据？', {
                                    title: "删除字段",
                                    btn: ['确认', '取消'] //按钮
                                }, function () {
                                    let selarray = grid.selection({
                                            type: 'row',
                                            method: 'getSelection'
                                        }),
                                        checked = [];
                                    for (var i = 0, len = selarray.length; i < len; i++) {
                                        checked.push({
                                            rowIndx: selarray[i].rowIndx
                                        });
                                    }
                                    grid.deleteRow({
                                        rowList: checked
                                    });

                                    rowIndex = null;
                                    layer.closeAll();
                                    layer.msg('操作成功');
                                }, function () {
                                    layer.closeAll();
                                });
                            } else {
                                layer.alert('请先选择行！');
                            }
                        }
                    }
                ]
            },
            scrollModel: {
                autoFit: true
            },
            selectChange: function (evt, ui) {
                console.log('selectChange', ui);
                // debugger;
                let address = ui.selection.address();
                rowIndex = address;
                // $("#select_change_div").html(JSON.stringify(address));
            },
            swipeModel: {
                on: false,
                type: null
            },
            editor: {
                select: true
            },
            bootstrap: {
                on: false
            },
            height: 'flex',
            showTitle: false,
            title: "<b>" + metaName + "</b>",
            history: function (evt, ui) {
                var $tb = this.toolbar();
                if (ui.canUndo != null) {
                    $("button.changes", $tb).button("option", {
                        disabled: !ui.canUndo
                    });
                }
                if (ui.canRedo != null) {
                    $("button:contains('Redo')", $tb).button("option", "disabled", !ui.canRedo);
                }
                $("button:contains('Undo')", $tb).button("option", {
                    label: 'Undo (' + ui.num_undo + ')'
                });
                $("button:contains('Redo')", $tb).button("option", {
                    label: 'Redo (' + ui.num_redo + ')'
                });
            },
            colModel: [
                {
                    dataIndx: "state",
                    maxWidth: 30,
                    minWidth: 30,
                    align: "center",
                    resizable: false,
                    type: 'checkBoxSelection',
                    cls: 'ui-state-default',
                    sortable: false,
                    editor: false,
                    dataType: 'bool',
                    cb: {
                        all: true,
                        header: true,
                        select: true
                    }
                },
                {
                    title: "名称",
                    width: 200,
                    dataType: "string",
                    dataIndx: "fieldComment",
                    validations: [{
                        type: 'minLen',
                        value: "1",
                        msg: "必填"
                    }]
                },
                {
                    title: "英文名",
                    width: 200,
                    dataType: "string",
                    dataIndx: "fieldName",
                    validations: [{
                        type: 'minLen',
                        value: "1",
                        msg: "必填"
                    }]
                },
                {
                    title: "表字段",
                    width: 200,
                    dataType: "string",
                    dataIndx: "columnName"
                },
                {
                    title: "类别",
                    width: 220,
                    dataType: "string",
                    dataIndx: "fieldType",
                    editor: {
                        type: "select",
                        labelIndx: "name",
                        valueIndx: "id",
                        prepend: {
                            "": ""
                        },
                        options: types
                    },
                    // validations: [{ type: 'minLen', value: "1", msg: "必填"}],
                    render: function (ui) {
                        var rowData = ui.rowData,
                            dataIndx = ui.dataIndx;

                        rowData.pq_cellcls = rowData.pq_cellcls || {};

                        let name = null;
                        $.each(types, function (index, obj) {
                            if (rowData[dataIndx] == obj.id) {
                                name = obj.name
                                return true;
                            }
                        });
                        return name;
                    }
                },
                {
                    title: "字段类型",
                    dataIndx: "fieldClass",
                    width: 220,
                    editor: {
                        type: "select",
                        labelIndx: "name",
                        valueIndx: "code",
                        prepend: {
                            "": ""
                        },
                        options: fieldClass
                    },
                    // validations: [{ type: 'minLen', value: "1", msg: "必填"}],
                    render: function (ui) {
                        var rowData = ui.rowData,
                            dataIndx = ui.dataIndx;

                        rowData.pq_cellcls = rowData.pq_cellcls || {};

                        let type = ui.rowData.fieldType;
                        if (type == '') {
                            type = "basic";
                        }
                        let fcls = getFieldClass(type)

                        let name = null;
                        $.each(fcls, function (index, obj) {
                            if (rowData[dataIndx] == obj.code) {
                                name = obj.name
                                return true;
                            }
                        });
                        return name;
                    }
                },
                {
                    title: "长度",
                    width: 100,
                    dataType: "integer",
                    dataIndx: "length"
                },
                {
                    title: "小数位",
                    width: 100,
                    dataType: "integer",
                    dataIndx: "decimalLength"
                },
                {
                    title: "关键字",
                    width: 100,
                    dataType: "bool",
                    align: "center",
                    dataIndx: "Keyword",
                    editor: false,
                    type: 'checkbox'
                },
                {
                    title: "唯一",
                    width: 100,
                    dataType: "bool",
                    align: "center",
                    dataIndx: "Repeat",
                    editor: false,
                    type: 'checkbox'
                },
                {
                    title: "非空",
                    width: 100,
                    dataType: "bool",
                    align: "center",
                    dataIndx: "NotEmpty",
                    editor: false,
                    type: 'checkbox'
                },
                {
                    title: "可导出",
                    width: 100,
                    dataType: "bool",
                    align: "center",
                    dataIndx: "canExcel",
                    editor: false,
                    type: 'checkbox',
                    validations: [{
                        type: 'nonEmpty',
                        msg: "Required"
                    }]
                },
                {
                    title: "隐藏参数",
                    width: 100,
                    dataType: "bool",
                    align: "center",
                    dataIndx: "apiHide",
                    editor: false,
                    type: 'checkbox',
                    validations: [{
                        type: 'nonEmpty',
                        msg: "Required"
                    }]
                },
                {
                    title: "操作",
                    editable: false,
                    width: 220,
                    sortable: false,
                    render: function (ui) {
                        // debugger
                        if (ui.rowIndx == 0) {
                            return `<a title="设置" class="edit_btn"><span class="icon setting"></span></a><span class="divider"></span><a title="复制" class='copy_btn'><span class="icon copy"></span></a><span class="divider"></span><a title="下移" class='down_btn'><span class="icon move_down"></span></a>`;
                        }
                        if (ui.rowIndx == data.length - 1) {
                            return `<a title="设置" class="edit_btn"><span class="icon setting"></span></a><span class="divider"></span><a title="复制" class='copy_btn'><span class="icon copy"></span></a><span class="divider"></span><a title="上移" class='up_btn'><span class="icon move_up"></span></a>`;
                        }
                        if (ui.rowIndx > 0 && ui.rowIndx < data.length - 1) {
                            return `<a title="设置" class="edit_btn"><span class="icon setting"></span></a><span class="divider"></span><a title="复制" class='copy_btn'><span class="icon copy"></span></a><span class="divider"></span><a title="上移" class='up_btn'><span class="icon move_up"></span></a><span class="divider"></span><a title="下移" class='down_btn'><span class="icon move_down"></span></a>`;
                            // return `<button type='button' class='copy_btn'></button>\<button type='button' class='up_btn'></button>\<button type='button' class='down_btn'></button>
                            //         <button type='button' class="edit_btn"></button>`;
                        }
                    },
                    postRender: function (ui) {

                        let copyData = {
                                ...{},
                                ...ui.rowData
                            },
                            copyIndx = ui.rowIndx + 1,
                            grid = this,
                            $cell = grid.getCell(ui);
                        copyData.fieldComment = copyData.fieldComment + "copy";
                        copyData.fieldName = copyData.fieldName + "copy";

                        if (copyData.columnName !== undefined && copyData.columnName !== "") {
                            copyData.columnName = copyData.columnName + "copy";
                        }
                        copyData.pq_rowselect = undefined;
                        copyData.state = false;

                        //copy button
                        $cell.find(".copy_btn")
                            // .button({ icons: { primary: 'ui-icon-copy'} })
                            .bind("click", function (evt) {
                                grid.addRow({
                                    newRow: copyData,
                                    rowIndx: copyIndx
                                });
                            });

                        //edit button
                        $cell.find(".edit_btn")
                            // .button({ icons: { primary: 'ui-icon-pencil'} })
                            .bind("click", function (evt) {
                                openModel(ui.rowIndx, ui.rowData, grid);
                                form.val('myForm', ui.rowData);
                            });

                        //up button
                        $cell.find(".up_btn")
                            // .button({ icons: { primary: 'ui-icon-arrowthick-1-n'} })
                            .bind("click", function (evt) {
                                // debugger
                                let upIndx = ui.rowIndx - 1,
                                    cruIndx = ui.rowIndx,
                                    upData = grid.getRowData({
                                        rowIndx: upIndx
                                    });
                                grid.deleteRow({
                                    rowIndx: upIndx
                                });
                                grid.addRow({
                                    newRow: upData,
                                    rowIndx: cruIndx
                                })

                            });
                        //down button
                        $cell.find(".down_btn")
                            // .button({ icons: { primary: 'ui-icon-arrowthick-1-s'} })
                            .bind("click", function (evt) {
                                let downIndx = ui.rowIndx + 1,
                                    cruIndx = ui.rowIndx,
                                    downData = grid.getRowData({
                                        rowIndx: cruIndx
                                    });
                                grid.deleteRow({
                                    rowIndx: cruIndx
                                });
                                grid.addRow({
                                    newRow: downData,
                                    rowIndx: downIndx
                                })
                            });
                    }
                }
            ],
            postRenderInterval: -1, //call postRender synchronously.
            // pageModel: { type: "remote", rPP: 20 },
            create: function () {
                this.widget().pqTooltip();
            },
            dataModel: {
                data: data
            }
        };

        var gridModel = function () {
            var self = this
            self.editRow = function (rd) {
                self.reset();
            };

            self.reset = function () {
                copy(master, self.company);
                self.focus(true);
            };
        }

        grid = pq.grid(option.elem, obj);

        option.grid = grid;

        return new domain_design_business(option);
    }


    exports(MOD_NAME, new domain_design_business());
});